from flask import Flask, render_template, request, redirect, url_for, session, jsonify, flash
import pandas as pd
from werkzeug.security import generate_password_hash, check_password_hash
from utils import get_weather_info, get_co2_data, get_wenxin_response

app = Flask(__name__)
app.secret_key = 'your_secret_key'

DATA_CSV_PATH = 'data.csv'

def load_users():
    return pd.read_csv('users.csv').to_dict('records')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = generate_password_hash(request.form['password'])
        users = load_users()
        if any(u['username'] == username for u in users):
            flash('用户名已存在。')
            return redirect(url_for('register'))
        user_id = len(users) + 1
        users.append({'id': user_id, 'username': username, 'password': password})
        pd.DataFrame(users).to_csv('users.csv', index=False)
        flash('注册成功，请登录。')
        return redirect(url_for('login'))
    return render_template('register.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        users = load_users()
        user = next((u for u in users if u['username'] == username), None)
        if user and check_password_hash(user['password'], password):
            session['user_id'] = user['id']
            session['username'] = user['username']
            return redirect(url_for('dashboard'))
        flash('无效的用户名或密码。')
        return redirect(url_for('login'))
    return render_template('login.html')

@app.route('/logout')
def logout():
    session.clear()
    flash('你已成功登出。')
    return redirect(url_for('index'))

@app.route('/dashboard')
def dashboard():
    if 'user_id' not in session:
        return redirect(url_for('login'))
    df = pd.read_csv(DATA_CSV_PATH)
    emission_data = df.to_dict('records')
    return render_template('dashboard.html', emission_data=emission_data)

@app.route('/get_emission_data')
def get_emission_data():
    df = pd.read_csv(DATA_CSV_PATH)
    data = {
        'labels': df['date'].tolist(),
        'actual_values': df['actual_value'].tolist(),
        'predicted_values': df['predicted_value'].tolist()
    }
    return jsonify(data)

@app.route('/get_weather', methods=['GET'])
def get_weather():
    city = request.args.get('city')
    suggest = request.args.get('suggest', 'false') == 'true'
    try:
        weather, temperature = get_weather_info(city)
        co2_data = get_co2_data()
        suggestion = None
        if suggest:
            suggestion = get_wenxin_response('出行建议', weather, co2_data)
        data = {
            'weather': weather,
            'temperature': f'{temperature}°C',
            'suggestions': suggestion
        }
        return jsonify(data)
    except ValueError as e:
        return jsonify({'error': str(e)})

if __name__ == '__main__':
    app.run(debug=True)
